package com.base.components.common.configuration.eureka;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean;
import org.springframework.security.crypto.encrypt.TextEncryptor;

import java.util.List;
import java.util.Map;

/**
 * EurekaClientConfigBeanPostProcessor
 *
 * @author <a href="drakelee1221@gmail.com">LiGeng</a>
 * @version v1.0.0
 * @date 2018-09-14 11:28
 */
//@Component
//@ConditionalOnClass(name = "org.springframework.cloud.netflix.eureka.EurekaClientConfigBean")
public class EurekaClientConfigBeanPostProcessor implements BeanPostProcessor {
  public static final String CIPHER = "{cipher}";
  public static final String COLON = ":";
  public static final String COMMA = ",";
  public static final String AT = "@";
  @Autowired(required = false)
  private TextEncryptor encryptor;
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if(bean instanceof EurekaClientConfigBean){
      EurekaClientConfigBean config = (EurekaClientConfigBean) bean;
      Map<String, String> serviceUrl = config.getServiceUrl();
      cleanUrls(serviceUrl);
    }
    return bean;
  }

  private void cleanUrls(Map<String, String> serviceUrl){
    for (Map.Entry<String, String> entry : serviceUrl.entrySet()) {
      String val = entry.getValue();
      boolean update = false;
      if(val.contains(" ")){
        update = true;
        val = StringUtils.deleteWhitespace(entry.getValue());
      }
      if(encryptor != null && val.contains(CIPHER)){
        update = true;
        String[] split = StringUtils.split(val, COMMA);
        List<String> list = Lists.newArrayList();
        for (String s : split) {
          list.add(cleanUrl(s));
        }
        val = StringUtils.join(list, COMMA);
      }
      if(update){
        entry.setValue(val);
      }
    }
  }

  private String cleanUrl(String url){
    String[] split = StringUtils.split(url, AT);
    List<String> s0List = Lists.newArrayList();
    for (String s0 : split) {
      if(s0.contains(CIPHER)){
        List<String> s1List = Lists.newArrayList();
        for (String s1 : StringUtils.split(s0, COLON)) {
          if(s1.contains(CIPHER)){
            s1 = encryptor.decrypt(s1);
          }
          s1List.add(s1);
        }
        s0 = StringUtils.join(s1List, COLON);
      }
      s0List.add(s0);
    }
    return StringUtils.join(s0List, AT);
  }
}
